package com.love_weinuo.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.love_weinuo.R;
import com.love_weinuo.bean.KeyWordCallbackBean;
import com.love_weinuo.databinding.ActivitySearchBinding;
import com.love_weinuo.ui.BaseActivity;
import com.love_weinuo.util.GsonUtil;
import com.love_weinuo.util.HTTPAPI;
import com.love_weinuo.util.LogUtil;
import com.love_weinuo.util.SpUtils;
import com.love_weinuo.util.ToastUtil;
import com.love_weinuo.util.dialog.InCommonDialog;
import com.love_weinuo.util.listener.OnBHClickListener;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by SensYang on 2019/02/28 15:46
 */

public class SearchActivity extends BaseActivity {

    String userId = (String) SpUtils.get("module_user_id", "");
    ActivitySearchBinding binding;
    String[] texts = new String[]{"潇洒哥最帅", "岁月最帅", "Richard大哥最帅", "群主最帅", "老子最帅", "。最帅", "老板是个禽兽"};
    int length;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_search);
        binding.setActivity(this);
        initView();
    }

    private void initView() {
        add(this);
        getKeyWord();
        length = texts.length;
        binding.rlModuleBack.setOnClickListener(this);
        binding.moduleFlowLayout.specifyLines(3);
        //        binding.flowlayout.addView(getSearchTextView(), lp);
        //        binding.flowlayout.specifyLines(3);
        //        binding.flowlayout.removeAllViews();
        //        final LayoutInflater mInflater = LayoutInflater.from(SearchActivity.this);



        binding.moduleDelete.setOnClickListener(this);
        binding.rlModuleSearch.setOnClickListener(this);
    }

    public TextView getSearchTextView(String str) {
        TextView tv = new TextView(this);
        tv.setPadding(dip2px(this, 13), 0, dip2px(this, 13), 0);
        tv.setTextColor(getResources().getColor(R.color.tv_3));
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
        tv.setText(str);
        tv.setGravity(Gravity.CENTER_VERTICAL);
        tv.setLines(1);
        tv.setBackgroundResource(R.drawable.draw_activity_login_register);
        return tv;
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.moduleDelete:
                InCommonDialog dialog = new InCommonDialog(this);
                dialog.setTitleText("删除所有搜索记录?");
                dialog.show();
                dialog.setOnBHClickListener(new OnBHClickListener() {
                    @Override
                    public void onConfirmClick() {
                        binding.moduleFlowLayout.removeAllViews();
                    }

                    @Override
                    public void onCloseClick() {

                    }
                });

                break;
            case R.id.rlModuleBack:
                finish();
                break;
            case R.id.rlModuleSearch:
                String result = binding.etModule.getText().toString().trim();
                if (TextUtils.isEmpty(result)) {
                    showInCommonDialog("请输入关键词");
                    return;
                }
                updateKeyWord(result);
                break;
            default:
        }
    }

    public void updateKeyWord(final String keyWord) {
        HTTPAPI.getInstance().updateKeyWord(userId, keyWord, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("上传搜索词成功" + s);
                startActivity(new Intent(SearchActivity.this, SearchResultActivity.class)
                        .putExtra("module_key_word", keyWord));
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                LogUtil.e("上传搜索词失败" + e.getMessage());
            }
        });
    }

    List<String> ans = new ArrayList<>();

    public void getKeyWord() {
        HTTPAPI.getInstance().getKeyWord(userId, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("获取关键词历史成功" + s);

                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if ("暂无搜索记录".equals(jsonObject.getString("msg"))) {
                        ToastUtil.showToast("暂无搜索记录");
                        return;
                    }

                    KeyWordCallbackBean bean = GsonUtil.GsonToBean(s, KeyWordCallbackBean.class);
                    ans.clear();
                    ans.addAll(bean.getResult().getKeyword());
                    binding.tfModule.setAdapter(new TagAdapter<String>(ans) {
                        @Override
                        public View getView(FlowLayout parent, int position, String s) {
                            return getSearchTextView(s);
                        }
                    });

                    binding.tfModule.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
                        @Override
                        public boolean onTagClick(View view, int position, FlowLayout parent) {
                            binding.etModule.setText(ans.get(position));
                            return true;
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //                int ranHeight = dip2px(SearchActivity.this, 25);
                //                ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ranHeight);
                //                lp.setMargins(dip2px(SearchActivity.this, 10), 0, dip2px(SearchActivity.this, 10), 0);
                //                for (String str : ans) {
                //                    binding.moduleFlowLayout.addView(getSearchTextView(str), lp);
                //                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                LogUtil.e("获取关键词历史失败" + e.getMessage());
            }
        });
    }


}
